import { setStore, getStore } from '../storage'
import { loginByUsername,checkToken } from "../../api/login"
import GLOBAL from "../../assets/js/const/global"
import md5 from 'js-md5'

const config = {
  state: {
    /**
     * userId   : 用户ID
     * username : 用户名
     * photoUrl : 用户头像地址
     */
    userInfo: {
      userId:       getStore({name:'userId'}) || '',
      username:     getStore({name:'username'}) || '',
      photoUrl:     getStore({name:'photoUrl'}) || GLOBAL.USER.PHOTO,
    },
    /**
     * loginState   : 登陆状态 | 1: 等待登陆 | 2:登陆成功 | -1:登陆失败
     * serverUrl    : 服务器地址
     * username     : 用户名
     * password     : 密码
     * accessToken  : Token
     * refreshToken : refreshToken
     */
    login: {
      loginState:   GLOBAL.LOGIN.STATE.NONE,  // 1: 等待登陆; 2:登陆成功; -1:登陆失败
      serverUrl:    getStore({name:'serverUrl'}) || '',
      username:     getStore({name:'username'}) || '',
      password:     getStore({name:'password'}) || '',
      accessToken:  getStore({name:'accessToken'}) || '',
      refreshToken: getStore({name:'refreshToken'}) || ''
    },
    /**
     * 对象存储,未开发
     */
    os: {
      type: getStore({name:'osType'}) || GLOBAL.OS.TYPE.ALIBABA_OSS,
      key: '',
      secret: '',
      defaultBucket: '',
      defaultUrl: ''
    },
    /**
     * resultType      : 黏贴类型  1:URL | 2:MARKDOWN | 3:IMAGE
     * changeNameState : 修改截图的名称
     */
    screenshot: {
      resultType:       getStore({name:'resultType'}) || GLOBAL.SS.RESULT_TYPE.IMAGE,
      changeNameState : getStore({name:'changeNameState'}) || false
    },
    theme: {
      type: getStore({name:'themeType'}) || 'light',
    },
    bossShield : {
      image : getStore({name:'bossShieldImage'}) || GLOBAL.BOSS_SHIELD.IMAGE
    }
  },
  actions: {
    /**
     * 用户登录
     * 成功 :
     *  1. 设置用户TOKEN
     *  2. 设置登陆状态
     *  3. 设置用户信息
     * 失败 :
     *  1. 登陆状态为失败
     *
     * @param userReq 用户名/密码
     * @constructor
     */
    LoginByUsername ({commit}, userReq) {
      const user = {
        username : userReq.username,
        password : md5(userReq.password)
      }
      return new Promise((resolve, reject) => {
        loginByUsername(user).then(resp => {
          commit('SET_TOKEN', resp.data)
          commit('SET_LOGIN_STATE', GLOBAL.LOGIN.STATE.SUCCESS)

          const userInfo = {
            userId  : resp.data.userInfo.userId,
            username: userReq.username,
            password: userReq.password,
            photoUrl: resp.data.userInfo.photoUrl == null || resp.data.userInfo.photoUrl === '' ? GLOBAL.USER.PHOTO : resp.data.userInfo.photoUrl
          }

          commit('SET_USER_INFO', userInfo)
          resolve()
        }).catch(error => {
          commit('SET_LOGIN_STATE', GLOBAL.LOGIN.STATE.FAIL)
          reject(error)
        })
      })
    },
    /**
     * 检查TOKEN
     * 应用启动时从缓存获取用户信息检查
     * 失败重置TOKEN信息
     */
    checkToken ({commit}) {
      return new Promise((resolve, reject) => {
        // eslint-disable-next-line
        checkToken().then(resp => {
          commit('SET_LOGIN_STATE', GLOBAL.LOGIN.STATE.SUCCESS)
          resolve()
        }).catch(error => {
          commit('CLEAR_CACHE_TOKEN')
          reject(error)
        })
      })
    }
  },
  mutations: {
    /*──────────────────────────────────────────────── login ─────────────────────────────────────────────────────*/
    /**
     * 保存服务器地址
     * @param serverUrl 服务器地址
     */
    SET_SERVER_URL: (state, serverUrl) => {
      state.login.serverUrl = serverUrl
      setStore({name: 'serverUrl', content: state.login.serverUrl, type: 'local'})
    },
    /**
     * 将 token 放入缓存
     * @param token token
     */
    SET_TOKEN: (state, token) => {
      state.login.accessToken  = token.accessToken
      state.login.refreshToken = token.refreshToken
      setStore({name: 'accessToken',  content: state.login.accessToken,  type: 'local'})
      setStore({name: 'refreshToken', content: state.login.refreshToken, type: 'local'})
    },
    /**
     * 设置登陆状态
     * @param loginState  1:等待登陆; 2:登陆成功; -1:登陆失败;
     */
    SET_LOGIN_STATE: (state, loginState) => {
      state.login.loginState = loginState
      setStore({name: 'loginState', content: state.login.loginState, type: 'local'})
    },
    /**
     * 将用户信息放入缓存
     * @param userInfo
     */
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo.userId   = userInfo.userId
      state.userInfo.username = userInfo.username
      state.userInfo.photoUrl = userInfo.photoUrl
      state.userInfo.osType   = userInfo.osType
      setStore({name: 'userId',   content: state.userInfo.userId,   type: 'local'})
      setStore({name: 'photoUrl', content: state.userInfo.photoUrl, type: 'local'})
      setStore({name: 'osType',   content: state.userInfo.osType, type: 'local'})

      state.login.username = userInfo.username
      state.login.password = userInfo.password
      setStore({name: 'username', content: state.login.username, type: 'local'})
      setStore({name: 'password', content: state.login.password, type: 'local'})
    },
    /*──────────────────────────────────────────────── screenshot ────────────────────────────────────────────────*/
    /**
     * 设置截图黏贴类型
     */
    SET_SCREENSHOT_RESULT_TYPE: (state, resultType) => {
      state.screenshot.resultType = resultType
      setStore({
        name: 'resultType',
        content: state.screenshot.resultType,
        type: 'local'
      })
    },
    /**
     * 修改截图名称
     */
    SET_SCREENSHOT_CHANGE_NAME: (state, changeNameState) => {
      state.screenshot.changeNameState = changeNameState
      setStore({
        name: 'changeNameState',
        content: state.screenshot.changeNameState,
        type: 'local'
      })
    },
    /*──────────────────────────────────────────────── os ────────────────────────────────────────────────────────*/
    SET_OS: (state, os) => {
      state.os.type = os.type
      setStore({name: 'osType', content: state.os.type, type: 'local'})
    },
    /*──────────────────────────────────────────────── theme ─────────────────────────────────────────────────────*/
    /**
     * 设置主题
     * @param state
     * @param themeType
     * @constructor
     */
    SET_THEME_TYPE: (state, themeType) => {
      state.theme.type = themeType
      setStore({
        name: 'themeType',
        content: state.theme.type,
        type: 'local'
      })
    },
    /*──────────────────────────────────────────────── boss shield ───────────────────────────────────────────────*/
    /**
     * 设置BOSS盾
     */
    SET_BOSS_SHIELD_IMAGE: (state, image) => {
      state.bossShield.image = image
      setStore({
        name: 'bossShieldImage',
        content: state.bossShield.image,
        type: 'local'
      })
    },
    /*──────────────────────────────────────────────── cache ─────────────────────────────────────────────────────*/
    /**
     * 清除用户缓存
     * @param state
     * @constructor
     */
    CLEAR_CACHE_USERINFO: (state) => {
      state.userInfo.userId    = ''
      state.userInfo.username  = ''
      state.userInfo.photoUrl  = GLOBAL.USER.PHOTO
      state.login.loginState   = GLOBAL.LOGIN.STATE.NONE
      setStore({name: 'loginState',   content: state.login.loginState,   type: 'local'})
    },
    /**
     * 清除TOKEN缓存
     * @param state
     * @constructor
     */
    CLEAR_CACHE_TOKEN: (state) => {
      state.login.accessToken           = ''
      state.login.refreshToken          = ''
      state.screenshot.resultType       = GLOBAL.SS.RESULT_TYPE.IMAGE
      state.screenshot.changeNameState  = false

      setStore({name: 'userId',   content: state.userInfo.userId,    type: 'local'})
      setStore({name: 'photoUrl', content: state.userInfo.photoUrl,  type: 'local'})
      setStore({name: 'username', content: state.login.username,     type: 'local'})
      setStore({name: 'password', content: state.login.password,     type: 'local'})

      setStore({name: 'loginState',   content: state.login.loginState,   type: 'local'})
      setStore({name: 'accessToken',  content: state.login.accessToken,  type: 'local'})
      setStore({name: 'refreshToken', content: state.login.refreshToken, type: 'local'})
    }
  }
}

export default config